<template>
  <div class="component-upload-image">
    <el-upload multiple :action="uploadImgUrl" list-type="picture-card" :on-success="handleUploadSuccess"
      :before-upload="handleBeforeUpload" :limit="limit" :on-error="handleUploadError" :on-exceed="handleExceed"
      name="files" :on-remove="handleRemove" :show-file-list="true" :headers="headers" :file-list="fileList"
      :on-preview="handlePictureCardPreview" :class="{ hide: this.fileList.length >= this.limit }">
      <i class="el-icon-plus"></i>
    </el-upload>

    <!-- 添加是否抠图功能 -->
    <el-checkbox v-model="is_koutu" label="是否抠图" style="margin-left: 20px" />
    <!-- 下拉选择抠图类型 -->
    <el-select v-model="koutuType" placeholder="请选择抠图类型" style="width: 120px;" v-if="is_koutu">
      <el-option label="简单" :value="0" />
      <el-option label="中等" :value="1" />
      <el-option label="高级" :value="2" />
    </el-select>

    <!-- 上传提示 -->
    <div class="el-upload__tip" slot="tip" v-if="showTip">
      请上传
      <template v-if="fileSize">
        大小不超过 <b style="color: #f56c6c">{{ fileSize }}MB</b>
      </template>
      <template v-if="fileType">
        格式为 <b style="color: #f56c6c">{{ fileType.join("/") }}</b>
      </template>
      的文件
    </div>

    <el-dialog :visible.sync="dialogVisible" title="预览" width="800" append-to-body>
      <img :src="dialogImageUrl" style="display: block; max-width: 100%; margin: 0 auto" />
    </el-dialog>
  </div>
</template>

<script>
import { getToken, getEnv } from "@/utils/auth";
import axios from 'axios'

export default {
  props: {
    value: [String, Object, Array],
    limit: {
      type: Number,
      default: 5,
    },
    fileSize: {
      type: Number,
      default: 5,
    },
    fileType: {
      type: Array,
      default: () => ["png", "jpg", "jpeg", 'gif'],
    },
    isShowTip: {
      type: Boolean,
      default: true,
    },
    is_koutu: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      number: 0,
      uploadList: [],
      dialogImageUrl: "",
      dialogVisible: false,
      hideUpload: false,
      baseUrl: "",
      uploadImgUrl: null,
      headers: {
        Authorization: "Bearer " + getToken()
      },
      fileList: [],
      koutuType: 2,
    };
  },
  watch: {
    value: {
      handler(val) {
        if (val) {
          const list = Array.isArray(val) ? val : this.value.split(",");
          console.log(val);

          this.fileList = list.map((item) => {
            if (typeof item === "string") {
              if (item.indexOf(this.baseUrl) === -1) {
                item = { name: this.baseUrl + item, url: this.baseUrl + item };
              } else {
                item = { name: item, url: item };
              }
            }
            return item;
          });
        } else {
          this.fileList = [];
          return [];
        }
      },
      deep: true,
      immediate: true,
    },
  },
  computed: {
    showTip() {
      return this.isShowTip && (this.fileType || this.fileSize);
    },
  },
  methods: {
    handleRemove(file, fileList) {
      const findex = this.fileList.map((f) => f.name).indexOf(file.name);
      if (findex > -1) {
        this.fileList.splice(findex, 1);
        this.$emit("input", this.listToString(this.fileList));
      }
    },
    // 上传成功回调
    handleUploadSuccess(res) {
      this.uploadList.push({ name: "res.fileName", url: res.data[0] });
      if (this.uploadList.length === this.number || res.code == 200) {
        this.$modal.closeLoading();
        this.$emit("input", res.data[0]);
        if (this.is_koutu) {
 
          this.$modal.loading("正在抠图，请稍候...");
          this.callRemoveBgApi(res.data[0]);
          this.uploadList = [];
          this.number = 0;
        } else {
          this.uploadList = [];
          this.number = 0;
        }
      }
    },
    // 调用抠图接口的方法
    callRemoveBgApi(imageUrl) {
      // this.$modal.showLoading();  // 显示加载动画
      axios.post('http://localhost:3000/remove-bg-url', { "imageUrl": imageUrl, type: this.koutuType })
        .then(response => {
          console.log('抠图接口调用成功:', response.data);

          const processedImageUrl = response.data.base64Image;  // 抠图完成后的图片 URL
          // 调用上传接口上传处理后的图片
          this.uploadProcessedImage__1(processedImageUrl);
        })
        .catch(error => {
           this.$modal.msgError('抠图接口调用失败:', error);
          console.error('抠图接口调用失败:', error);
          this.$modal.closeLoading();  // 隐藏加载动画
        });
    },
    // 上传处理好的图片
    // 上传处理好的图片
    uploadProcessedImage__1(processedImageUrl) {
      // 创建一个 FormData 对象
      const formData = new FormData();
      const base64Image = processedImageUrl.split(',')[1];  // 假设 processedImageUrl 是类似 "data:image/png;base64,..." 的字符串
      const blob = this.base64ToBlob(base64Image, 'image/png');  // 'image/png' 是 MIME 类型
      // 将图片数据添加到 FormData 对象中
      // 注意：processedImageUrl 应该是 Blob 或 File 对象
      //将：processedImageUrl转化为Blob对象
      formData.append('files', blob, 'processed-image.png');
      //添加时间戳
      formData.append('timestamp', new Date().getTime());


      // 发起 POST 请求
      axios.post(this.uploadImgUrl, formData, {
        headers: {
          Authorization: "Bearer " + getToken(),
          'Content-Type': 'multipart/form-data'
        }
      })
        .then(response => {
          console.log(response.data.data[0]);
          // this.fileList.push(res.data.data[0]);
          this.$emit("input", response.data.data[0]);
          this.$modal.closeLoading();  // 隐藏加载动画
        })
        .catch(error => {
          console.error('处理后的图片上传失败:', error);
          this.$modal.closeLoading();  // 隐藏加载动画
        });
    },
    base64ToBlob(base64, mime) {
      const sliceSize = 1024;
      const byteCharacters = atob(base64);
      const byteArrays = [];

      for (let offset = 0; offset < byteCharacters.length; offset += sliceSize) {
        const slice = byteCharacters.slice(offset, offset + sliceSize);
        const byteNumbers = new Array(slice.length);
        for (let i = 0; i < slice.length; i++) {
          byteNumbers[i] = slice.charCodeAt(i);
        }
        const byteArray = new Uint8Array(byteNumbers);
        byteArrays.push(byteArray);
      }

      return new Blob(byteArrays, { type: mime });
    },


    handleBeforeUpload(file) {
      let isImg = false;
      if (this.fileType.length) {
        let fileExtension = "";
        if (file.name.lastIndexOf(".") > -1) {
          fileExtension = file.name.slice(file.name.lastIndexOf(".") + 1);
        }
        isImg = this.fileType.some((type) => {
          if (file.type.indexOf(type) > -1) return true;
          if (fileExtension && fileExtension.indexOf(type) > -1) return true;
          return false;
        });
      } else {
        isImg = file.type.indexOf("image") > -1;
      }

      if (!isImg) {
        this.$modal.msgError(
          `文件格式不正确, 请上传${this.fileType.join("/")}图片格式文件!`
        );
        return false;
      }
      if (this.fileSize) {
        const isLt = file.size / 1024 / 1024 < this.fileSize;
        if (!isLt) {
          this.$modal.msgError(`上传图片大小不能超过 ${this.fileSize} MB!`);
          return false;
        }
      }
      this.$modal.loading("正在上传图片，请稍候...");
      this.number++;
    },
    handleExceed() {
      this.$modal.msgError(`上传文件数量不能超过 ${this.limit} 个!`);
    },
    handleUploadError() {
      this.$modal.msgError("上传图片失败，请重试");
      this.$modal.closeLoading();
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    listToString(list, separator) {
      let strs = "";
      separator = separator || ",";
      for (let i in list) {
        strs += list[i].url.replace(this.baseUrl, "") + separator;
      }
      return strs != "" ? strs.substr(0, strs.length - 1) : "";
    },
  },
  created() {
    this.uploadImgUrl = getEnv() == '1' ? process.env.VUE_APP_BASE_API : process.env.VUE_APP_TEST_API;
    this.uploadImgUrl = this.uploadImgUrl + '/system/admin/uploadFile';
  }
};
</script>
